<template>
	<div>
		<commons-alert @alert-dismissed="alertDismissed" :variant="alert.variant" :dismissCountDown="alert.dismissCountDown">{{alert.message}}</commons-alert>
		<page-title>{{title}}</page-title>

		<b-container fluid>
			<b-row>
				<b-col cols="6" class="p-0">
					<b-button v-show="oprs && oprs.new" variant="info" size="sm" @click="createNewItem" class="m-1">
						<b-icon icon="plus-circle"></b-icon> 新建
					</b-button>
					<b-button v-show="selectable && oprs && oprs.mdel" :disabled="table.selected.length === 0" variant="info" size="sm"
					 @click="deleteSelected" class="m-1">
						<b-icon icon="trash"></b-icon> 删除
					</b-button>
					<b-button v-show="selectable && oprs && oprs.cupdate" :disabled="table.selected.length === 0" variant="info" size="sm"
					 @click="editSelected" class="m-1">
						<b-icon icon="pencil-square"></b-icon> 修改
					</b-button>
					<b-button v-show="selectable && oprs && oprs.view" :disabled="table.selected.length === 0" variant="info" size="sm"
					 @click="viewSelected" class="m-1">
						<b-icon icon="receipt"></b-icon> 详情
					</b-button>
					<b-button v-show="selectable && showSelectBtn && (selectMode === 'range' || selectMode ==='multi')" variant="info"
					 size="sm" @click="selectAll" class="m-1">
						<b-icon icon="check-all"></b-icon> 全选
					</b-button>
					<b-button v-show="selectable && showSelectBtn" :disabled="table.selected.length === 0" variant="info" size="sm"
					 @click="unselectAll" class="m-1">
						<b-icon icon="x-circle"></b-icon> 取消选择
					</b-button>
					<slot name="top-buttons"></slot>
				</b-col>
				<b-col cols="6">
					<b-form v-show="queryBar">
						<b-container fluid>
							<b-row>
								<b-col cols="5">
									<slot name="second-query"></slot>
								</b-col>
								<b-col cols="4">
									<slot name="primary-query"></slot>
								</b-col>
								<b-col cols="3">
									<b-button class="m-1" size="sm" variant="info" @click="doQuery">查询</b-button>
									<b-button class="m-1" size="sm" variant="info" @click="queryReset">重置</b-button>
									<b-button v-show="moreCondition" v-b-tooltip.hover title="更多查询条件" v-b-toggle.more-query-conditions class="m-1"
									 size="sm" variant="light">
										<span class="when-closed">
											<b-icon icon="chevron-double-down"></b-icon>
										</span>
										<span class="when-open">
											<b-icon icon="chevron-double-up"></b-icon>
										</span>
									</b-button>
								</b-col>
							</b-row>
							<b-collapse class="more-condition" v-show="moreCondition" id="more-query-conditions">
								<slot name="other-query"></slot>
							</b-collapse>
						</b-container>
					</b-form>
				</b-col>
			</b-row>
		</b-container>

		<slot name="after-tools-before-table"></slot>

		<b-table class="m-1" bordered striped hover small primary-key="id" :selectable="selectable" :items="items" :busy="table.isBusy"
		 :fields="completeFields" :select-mode="selectMode" ref="selectableTable" @row-selected="onRowSelected">
			<template v-slot:cell(selected)="{ rowSelected }">
				<template v-if="rowSelected">
					<span aria-hidden="true">&check;</span>
					<span class="sr-only">已选择</span>
				</template>
				<template v-else>
					<span aria-hidden="true">&nbsp;</span>
					<span class="sr-only">未选择</span>
				</template>
			</template>
			<template v-slot:cell(index)="data">
				{{ data.index + 1 }}
			</template>
			<template v-slot:cell(actions)="row">
				<b-button :disabled="row.item.$updateDisable" v-show="oprs.update" v-b-tooltip.hover title="修改" variant="info" size="sm" @click="editItem(row.item)"
				 class="mr-1">
					<b-icon icon="pencil-square"></b-icon>
				</b-button>
				<b-button :disabled="row.item.$delDisable" v-show="oprs.del" v-b-tooltip.hover title="删除" variant="info" size="sm" @click="deleteItem(row.item)"
				 class="mr-1">
					<b-icon icon="trash"></b-icon>
				</b-button>
				<b-button :disabled="row.item.$viewDisable" v-show="oprs.view" v-b-tooltip.hover title="详情" variant="info" size="sm" @click="viewItem(row.item)"
				 class="mr-1">
					<b-icon icon="receipt"></b-icon>
				</b-button>
				<slot name="more-actions" :row="row"></slot>
			</template>

			<template v-for="cc in customCells" v-slot:[cc]="data">
				<slot :name="'custom-cells-' + cc" :data="data"></slot>
			</template>

			<template v-slot:table-busy>
				<div class="text-center text-danger my-2">
					<b-spinner class="align-middle"></b-spinner>
					<strong>加载中...</strong>
				</div>
			</template>
		</b-table>

		<b-container v-show="pagable" fluid>
			<b-row>
				<b-col v-show="showPageInfo" cols="6">
					<div>
						<b-select class="page-select" v-model="pageObj.perPage">
							<option selected="selected" value="15">每页15条</option>
							<option value="25">每页25条</option>
							<option value="50">每页50条</option>
							<option value="100">每页100条</option>
							<option value="200">每页200条</option>
						</b-select>
						<span> 共{{pageObj.totalRows}}条记录</span>
					</div>
				</b-col>
				<b-col :cols="showPageInfo ? 6 : 12">
					<b-pagination v-model="pageObj.currentPage" :total-rows="pageObj.totalRows" :per-page="pageObj.perPage" align="right"
					 first-number last-number size="md">
					</b-pagination>
				</b-col>
			</b-row>
		</b-container>

	</div>
</template>

<script>
	import axios from 'axios'
	import gl from './global_variable.js'
	import PageTitle from './ContentPageTitle.vue'
	import CommonsAlert from './Alert.vue'

	export default {
		name: "my-table",
		components: {
			PageTitle,
			CommonsAlert
		},
		props: {
			title: {
				type: String
			},
			pagable: {
				type: Boolean,
				default: false
			},
			showPageInfo: {
				type: Boolean,
				default: true
			},
			perPage: {
				type: Number,
				default: 15
			},
			totalRows: {
				type: Number,
				default: 0
			},
			selectable: {
				type: Boolean,
				default: false
			},
			showSelectBtn: {
				type: Boolean,
				default: true
			},
			selectMode: {
				type: String,
				default: 'multi',
				validator: function(value) {
					return ['single', 'range', 'multi'].indexOf(value) !== -1
				}
			},
			index: {
				type: Boolean,
				default: false
			},
			oprable: {
				type: Boolean,
				default: true
			},
			oprs: {
				type: Object,
				default: function(){
					return {
						new: true,
						update: true,
						cupdate: true,
						view: true,
						mdel: true,
						del: true
					}
				}
			},
			oprBtnsDisabled: {
				type: Object,
				default: function(){
					return {
						new: false,
						update: false,
						view: false,
						mdel: false,
						del: false
					}
				}
			},
			items: {
				type: Array
			},
			queryBar: {
				type: Boolean,
				default: false
			},
			moreCondition: {
				type: Boolean,
				default: false
			},
			fields: {
				type: Array
			},
			customCells: {
				type: Array
			},
			actionsColClass: {
				type: Array,
				default: function() {
					return []
				}
			}
		},
		data: function() {
			return {
				alert: {
					message: "",
					variant: "warning",
					dismissCountDown: 0
				},
				table: {
					isBusy: false,
					selected: [],
					initSelectedIds: []
				},
				pageObj: {
					currentPage: 1,
					perPage: 15,
					totalRows: 0
				}
			}
		},
		created: function() {

		},
		watch: {
			perPage: function(val) {
				this.pageObj.perPage = val
			},
			totalRows: function(val) {
				this.pageObj.totalRows = val
			},
			'pageObj.currentPage': function(val) {
				this.$emit("table-page", {
					currentPage: Number.parseInt(val),
					perPage: Number.parseInt(this.pageObj.perPage)
				})
			},
			'pageObj.perPage': function(val) {
				this.$emit("table-page", {
					currentPage: 1,
					perPage: Number.parseInt(val)
				})
			},
			items: function(values){
				var that = this
				setTimeout(function(){
					that.internalDoSelectRows()
				}, 500)
			}
		},
		methods: {
			internalDoSelectRows: function(){
				if(this.table.initSelectedIds.length > 0){
					for (var x = 0; x < this.items.length; x++) {
						if(this.table.initSelectedIds.indexOf(this.items[x].id) !== -1){
							this.$refs.selectableTable.selectRow(x)
						}
					}
				}
			},
			setSelectRows: function(dataIds){
				this.table.initSelectedIds = dataIds
			},
			onRowSelected: function(items) {
				this.table.selected = items;
				this.$emit("item-selected", this.table.selected)
			},
			editItem: function(item) {
				this.$emit("item-update", item)
			},
			deleteItem: function(item) {
				this.$emit("item-delete", item)
			},
			viewItem: function(item) {
				this.$emit("item-view", item)
			},
			deleteSelected: function() {
				this.$emit("items-delete", this.table.selected)
			},
			editSelected: function() {
				this.$emit("item-update", this.table.selected[this.table.selected.length - 1])
			},
			viewSelected: function() {
				this.$emit("item-view", this.table.selected[this.table.selected.length - 1])
			},
			selectAll: function() {
				this.$refs.selectableTable.selectAllRows()
			},
			unselectAll: function() {
				this.$refs.selectableTable.clearSelected()
			},
			createNewItem: function() {
				var currentSelectedItem = this.table.selected.length > 0 ? this.table.selected[this.table.selected.length - 1] :
					null
				this.$emit("item-new", currentSelectedItem)
			},
			doQuery: function() {
				this.$emit("do-query")
			},
			queryReset: function() {
				this.$emit("do-reset-query")
			},
			alertDismissed: function() {
				this.alert.dismissCountDown = 0
				this.$emit("table-alert-dismissed-" + this.alert.variant)
			},
			onDeleteSuccess: function(message, seconds) {
				this.alert.message = message || "删除成功."
				this.alert.variant = "success"
				this.alert.dismissCountDown = seconds || 3
			},
			onDeleteError: function(message, seconds) {
				this.alert.message = message || "删除失败."
				this.alert.variant = "warning"
				this.alert.dismissCountDown = seconds || 3
			},
			onQueryError: function(message, seconds) {
				this.alert.message = message || "数据加载失败."
				this.alert.variant = "warning"
				this.alert.dismissCountDown = seconds || 3
			},
			onAnyError: function(message, seconds){
				this.alert.message = message || "操作失败."
				this.alert.variant = "warning"
				this.alert.dismissCountDown = seconds || 3
			},
			onAnySuccess: function(message, seconds) {
				this.alert.message = message || "操作成功."
				this.alert.variant = "success"
				this.alert.dismissCountDown = seconds || 3
			}
		},
		computed: {
			completeFields: function() {
				var columns = []
				if (this.selectable) {
					columns.push({
						key: "selected",
						label: "",
						"class": ["selected-col", "text-center"]
					})
				}
				if (this.index) {
					columns.push({
						key: "index",
						label: "#",
						"class": ["index-col", "text-center"]
					})
				}
				columns = columns.concat(this.fields)
				if (this.oprable) {
					columns.push({
						key: "actions",
						label: "",
						"class": ["text-center", "actions-col"].concat(this.actionsColClass)
					})
				}
				return columns
			}
		}
	}
</script>

<style>
	.actions-col {
		width: 11.25rem;
	}

	.index-col {
		width: 3.125rem;
	}

	.selected-col {
		width: 1.875rem;
	}

	.page-select {
		width: auto !important;
	}

	.collapsed>.when-open,
	.not-collapsed>.when-closed {
		display: none;
	}

	.table th,
	.table td {
		vertical-align: middle !important;
	}
	
	.more-condition {
		border: 0.0625rem dotted gray;
		border-radius: 0.625rem;
	}
</style>
